package gui;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;

import javax.imageio.ImageIO;
import javax.swing.JComponent;

import objetos.Posicao;

public class Field extends JComponent implements Observer{

	private int NUM_COL;
	private int NUM_LIN;
	private int SQUARE_SIZE;
	private LinkedList<Posicao> posicoes;

	public Field(int nUM_COL, int nUM_LIN, int sNAKE_SIZE) {
		super();
		NUM_COL = nUM_COL;
		NUM_LIN = nUM_LIN;
		SQUARE_SIZE = sNAKE_SIZE;
		posicoes = new LinkedList<>();
		for(int i = 0 ; i <= NUM_COL * NUM_LIN; i++)
			posicoes.add(new Posicao(i, false));
	}

	public int getNUM_COL() {
		return NUM_COL;
	}

	public int getNUM_LIN() {
		return NUM_LIN;
	}

	public int getSNAKE_SIZE() {
		return SQUARE_SIZE;
	}

	public LinkedList<Posicao> getPosicoes() {
		return posicoes;
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		for(int i= 0 ; i <= NUM_LIN; i++)
			for(int j = 0; j <= NUM_COL; j++){
				int TAMANHO_JANELA_HORIZONTAL = NUM_COL * SQUARE_SIZE;
				int TAMANHO_JANELA_VERTICAL = NUM_LIN * SQUARE_SIZE;
				g.drawLine(0 , i * SQUARE_SIZE , TAMANHO_JANELA_HORIZONTAL , i *SQUARE_SIZE);
				g.drawLine(j * SQUARE_SIZE, 0 , j * SQUARE_SIZE , TAMANHO_JANELA_VERTICAL);
			}
//		File file = new File("C:\\Users\\Susana\\Desktop\\ISCTE\\PCD\\Snake\\rsz_apple-icon.png");
//		BufferedImage image = null;
//		try {
//			image = ImageIO.read(file);
//		} catch (IOException e) {
//			e.printStackTrace();
//		} 
		
//		g.drawImage(image, 21,21, null);
		
		for(Posicao p: posicoes){
			if(p.isOcupada()){
				int x = p.getX();
				int y = p.getY();
				g.fillOval(x, y, 20, 20);
				//g.fillRect(x, y, 20, 20);
				repaint();
			}
			if(p.hasApple()){
				int x = p.getX();
				int y = p.getY();
				g.drawImage(p.getApple().getImage(), x+1,y+1, null);
			}

		}
		
	}

	public synchronized void pintarPosicao(Posicao p){
		posicoes.get(p.getIndice()).setOcupada(true);
	}
	public synchronized void removerPosicao(Posicao p){
		posicoes.get(p.getIndice()).setOcupada(false);
	}


	@Override
	public void update(Observable arg0, Object arg1) {	
		posicoes = (LinkedList<Posicao>) arg1;
	}

}
